//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.domain.*;
import com.wsd.smartcarwasher.service.*;
import com.wsd.smartcarwasher.util.*;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.security.MD5Encoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
public class PayController {
    private static final Logger logger = LoggerFactory.getLogger(PayController.class);
    @Resource
    private WxPayService wxPayService;
    @Resource
    private WxService wxService;
    @Resource
    private OrderService orderService;
    @Resource
    private CardOrderService cardOrderService;
    @Resource
    private CardService cardService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private TChargeRecordService chargeRecordService;
    @Resource
    private  RefundRecordService refundRecordService;

    public PayController() {
    }

    @ResponseBody
    @RequestMapping(
            value = {"/v1/pay/prepay"},
            method = {RequestMethod.GET},
            produces = {"application/json;charset=UTF-8"}
    )
    public ModelMap prePay(String orderSn, HttpServletRequest request) {
        String openId = "do7AZa5AUlUyHLILiDlrtjyg__kwc";
        if (StringUtils.isBlank(openId)) {
            return ReturnUtil.Error(ResultState.LOGIN_AGAIN.getMsg());
        } else {
            openId = openId.replace("\"", "").trim();
            String clientIP = CommonUtil.getClientIp(request);
            Order order = this.orderService.queryOrderInfoByOrderSn(orderSn);
            if (order == null) {
                order = this.cardOrderService.queryOrderInfoByOrderSn(orderSn);
            }

            return this.wxPayService.payByWx(openId, clientIP, (Order)order);
        }
    }

    @RequestMapping(
            value = {"/v1/pay/call_back"},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public String notifyWeiXinPay(HttpServletRequest request) {
        logger.info("微信支付回调");
        Map params = null;

        String result;
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            boolean var6 = false;

            int len;
            while((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }

            result = new String(outSteam.toByteArray(), "utf-8");
            logger.info("result===" + result);
            params = CommonUtil.parseXml(result);
            outSteam.close();
            inStream.close();
        } catch (Exception var9) {
            logger.error("解析微信支付成功回调参数失败");
        }
        Map<String, String> return_data = new HashMap();
        if (params != null && this.wxPayService.isWxPaySign(params)) {
            logger.info("===============付款成功==============");
            String orderSn = null;

            try {
                logger.info("params:" + params.toString());
                String total_fee = (String)params.get("total_fee");
                orderSn = (String)params.get("out_trade_no");
                Date accountTime = DateUtil.stringToDate((String)params.get("time_end"), "yyyyMMddHHmmss");
                result = (String)params.get("transaction_id");
            } catch (Exception var8) {
                logger.error("catch error when pay call back");
            }

            CardOrder order = this.cardOrderService.queryOrderInfoByOrderSn(orderSn);
            if (order == null) {
                OrderInfo orderInfo = new OrderInfo();
                orderInfo.setOrderSn(orderSn);
                this.orderService.payFinishOrder(orderInfo);
            } else {
                this.cardOrderService.payFinishOrder(order);
            }
            return_data.put("return_code", "SUCCESS");
            return_data.put("return_msg", "OK");
            return CommonUtil.mapToXML(return_data);
        } else {
            return_data.put("return_code", "FAIL");
            return_data.put("return_msg", "return_code不正确");
            return CommonUtil.mapToXML(return_data);
        }
    }


    /**
     * 微信退款回调通知
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(
            value = {"/v1/rerund/call_back"},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public String notifyWeiXinRefund(HttpServletRequest request) throws Exception {
        Map params = null;
        String result;
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            boolean var6 = false;
            int len;
            while((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            result = new String(outSteam.toByteArray(), "utf-8");
            logger.info("result===" + result);
            params = CommonUtil.parseXml(result);
            outSteam.close();
            inStream.close();
        } catch (Exception var9) {
            logger.error("解析回调参数失败");
        }

        Map<String, String> return_data = new HashMap();
        if (params != null) {

            String text= NTWXZF.aesDecrypt((String)params.get("req_info"),"woniuzhinengkejiyouxiangongsi000");
            Map<String, String > stringObjectMap=CommonUtil.parseXml(text);
            System.out.println("参数为"+stringObjectMap);
            if(stringObjectMap.containsKey("out_trade_no"))
            {
                String ordersn=stringObjectMap.get("out_trade_no");
                CardOrder cardOrder=this.cardOrderService.queryOrderInfoByOrderSn(ordersn);
                TRefundRecord tRefundRecord=refundRecordService.checkUserExistRefundApply(ordersn);
                if(!StringUtil.isNullOrEmpty(tRefundRecord))
                {
                    if(cardOrder.getCardId()!=null){
                        int row =  cardService.rollUserCard(cardOrder);
                    }
                    orderService.refundCardOrder(cardOrder.getOrderSn());
                    this.refundRecordService.userApplyRefundFinish(ordersn,JSONUtils.beanToJson(stringObjectMap));
                }
            }
            return_data.put("return_code", "SUCCESS");
            return_data.put("return_msg", "OK");
            return CommonUtil.mapToXML(return_data);
        } else {
            return_data.put("return_code", "FAIL");
            return_data.put("return_msg", "return_code不正确");
            return CommonUtil.mapToXML(return_data);
        }
    }





    @RequestMapping(
            value = {"/v1/charge/call_back"},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public String notifyWeiXinCharge(HttpServletRequest request) {
        logger.info("微信支付回调----充值订单");
        Map params = null;

        String result;
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            boolean var6 = false;

            int len;
            while((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }

            result = new String(outSteam.toByteArray(), "utf-8");
            logger.info("result===" + result);
            params = CommonUtil.parseXml(result);
            outSteam.close();
            inStream.close();
        } catch (Exception var9) {
            logger.error("解析微信支付成功回调参数失败");
        }
        Map<String, String> return_data = new HashMap();
        if (params != null && this.wxPayService.isWxPaySign(params)) {
            logger.info("===============付款成功==============");
            String orderSn = null;

            try {
                logger.info("params:" + params.toString());
                String total_fee = (String)params.get("total_fee");
                orderSn = (String)params.get("out_trade_no");
                Date accountTime = DateUtil.stringToDate((String)params.get("time_end"), "yyyyMMddHHmmss");
                result = (String)params.get("transaction_id");
            } catch (Exception var8) {
                logger.error("catch error when pay call back");
            }
            QueryWrapper<TChargeRecord> chargeRecordQueryWrapper=new QueryWrapper<>();
            chargeRecordQueryWrapper.eq("transactionNo",orderSn);
            TChargeRecord chargeRecord=this.chargeRecordService.getOne(chargeRecordQueryWrapper);
            if(!StringUtil.isNullOrEmpty(chargeRecord))
            {
                this.chargeRecordService.payFinishOrder(chargeRecord);
            }
            return_data.put("return_code", "SUCCESS");
            return_data.put("return_msg", "OK");
            return CommonUtil.mapToXML(return_data);
        } else {
            return_data.put("return_code", "FAIL");
            return_data.put("return_msg", "return_code不正确");
            return CommonUtil.mapToXML(return_data);
        }
    }




}
